<?php

namespace App\Package\Finance;

use App\Package\Finance\Traits\ExpressionHandler;
use App\Package\Finance\Contracts\ExpressionContract;

/**
 * 表达式处理逻辑
 *
 * Date: 2018/6/6
 * @author George
 * @package App\Package\Finance
 */
class Expression implements ExpressionContract
{
	use ExpressionHandler;

	/**
	 * 定义字面量
	 *
	 * @var $literals
	 * Date: 2018/6/6
	 * @author George
	 */
	private $literals;

	/**
	 * 定义表达式
	 *
	 * @var $expression
	 * Date: 2018/6/6
	 * @author George
	 */
	private $expression;

	/**
	 * Expression constructor.
	 * @param $literals
	 */
	public function __construct(array $literals)
	{
		$this->literals = $literals;
	}

	/**
	 * 返回结果
	 *
	 * Date: 2018/6/13
	 * @author George
	 * @return mixed
	 */
	public function result()
	{
		foreach ($this->literals as $literal) {
			// 判断表达式字面量的类型
			switch ($literal['type']) {
				// 如果是数字，直接参与运算
				case 'number':
					$this->expression = $this->expression . $literal['value'];
					break;
				// 如果是运算符，直接参与运算
				case 'operator':
					$this->expression = $this->expression . ' ' . $literal['label'];
					break;
				// 如果是自定义字段，则调用字段处理类进行处理并返回最终结果值
				case 'field':
					$fieldHandler = new FieldHandler($literal);
					$filed = $fieldHandler->handle();
					$this->expression = $this->expression . ' ' . $filed['value'];
					break;
			}
		}

		return eval('return ' . $this->expression . ';');
	}
}
